import "./batch.scss";
import { useState, useEffect } from "react";
import classNames from "classnames";
import { Header } from "../header/header";
import { Card } from "../card/card";
import { Tag } from "../tag/tag";
import { TextField } from "../textfield/textfield";
import { useExeclToJson, ExcelJsonType } from "@/utils/hook";
import { UploadButton } from "../button/button";
import { BatchLogin } from "./batchLogin/batchLogin";
import { Button } from "../button/button";
import { useExportExecl } from "@/utils/hook";
import { getLoginStatusData } from "@/api/batch/batch";
import { getListUserData } from "@/api/batch/batch";
import { Select } from "../select/select";

interface Item {
  code: number;
  [key: string]: any;
}
const Batch = () => {
  // 存储json文件
  const [jsonData, setJsonData] = useState<
    ExcelJsonType | ExcelJsonType[] | undefined
  >();
  // 第一次登录数据
  const [firstLoginData, setFirstLoginData] = useState<Item[]>([]);

  // 第二次登陆数据
  const [, setLoginErrorData] = useState<Item[]>([]);

  const [isActive, setIsActive] = useState(1);

  const [webSocket] = useState<WebSocket | null>(null);

  const excelToJson = useExeclToJson();

  const exportExecl = useExportExecl();

  const barClassName = (payload: number): string => {
    return classNames("batch_bar_item", isActive == payload && "active");
  };
  useEffect(() => {
    if (jsonData) {
      batchLogin();
    }
  }, [jsonData]);

  const batchLogin = async () => {
    let res = await getLoginStatusData(jsonData?.slice(6, 10));
    // @ts-expect-error
    if (res.message) {
      listUserData();
      startSource();
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    excelToJson(e, setJsonData);
    // batchLogin();
  };

  // 提取二次登录数据再次发送请求
  const errorAccSecondRequest = () => {
    let filteredArray = firstLoginData.filter((item) => {
      return item.logincode !== 0;
    });
    webSocket?.send(JSON.stringify(filteredArray));
    setLoginErrorData(filteredArray);
  };

  // 获取表格数据
  const listUserData = async () => {
    let res = await getListUserData();
    console.log(res);

    setFirstLoginData(res.data.list);
  };

  const startSource = () => {
    if ("EventSource" in window) {
      var source = new EventSource("http://text.hangyunda.com/sse");
      source.onmessage = function (e) {
        console.log(e.data);
        if (e.data) {
        }
      };

      source.onerror = function (e: any) {
        if (e.readyState == EventSource.CLOSED) {
          console.log("连接关闭...");
        }
      };
      source.onopen = () => {
        console.log("链接打开");
      };
    } else {
      console.log("没有sse");
    }
  };

  return (
    <>
      <Select>
        <Select.Item value={1}>1</Select.Item>
        <Select.Item value={2}>2</Select.Item>
        <Select.Item value={3}>3</Select.Item>
        <Select.Item value={4}>4</Select.Item>
      </Select>
      <div className="dashboard_batch_box">
        <Card className="batch_header">
          <Header />
        </Card>

        <div className="batch_tablebar">
          <Tag className={barClassName(1)} onClick={() => setIsActive(1)}>
            账号批量登录
          </Tag>
          <Tag className={barClassName(2)} onClick={() => setIsActive(2)}>
            账号批量注册
          </Tag>
        </div>

        <Card className="batch_search" radiusPostion="top">
          <TextField
            type="select"
            placeholder="请输入用户名"
            onKeyup={(e) => console.log(e)}
            id={15978613541}
          />
          <div className="btn_box">
            <UploadButton
              label={"添加用户 (Execl表格)"}
              onChange={(e) => handleChange(e)}
              disable={Boolean(jsonData)}
            />
            <Button
              label={"导出登录异常数据为Execl"}
              onClick={() => exportExecl(jsonData, "异常数据列表")}
            />
            <Button
              label={"异常账号二次登录"}
              onClick={errorAccSecondRequest}
            />
          </div>
        </Card>
        <div className="batch_table">
          <BatchLogin loginData={firstLoginData} />
        </div>
      </div>
    </>
  );
};

export default Batch;
